<?php
class Kdt_push_model extends Base_Model
{
    const KDT_TRADES_TABLE  = 'kdt_trades';
    const KDT_ORDERS_TABLE  = 'kdt_orders';
    const KDT_CONSIGNS_TABLE= 'kdt_consigns';
    const KDT_SALESMAN = 'kdt_salesman';
    const KDT_SM_TRADE = 'kdt_salesman_trades';
    const KDT_SM_ORDER = 'kdt_salesman_orders';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function insertData($table,$data)
    {
        return $this->db->insert_batch($table,$data);
    }

    public function checkExsit($table,$ret,$where=array())
    {
        $res = $this->db->select($ret)->from($table)->where($where)->get()->row_array();
        if (empty($res)) return false;
        else return $res;
    }

    public function insertTradesOrdersConsigns($data)
    {
        $this->db->trans_begin();
        $this->insertData(self::KDT_TRADES_TABLE,$data['trades']);
        $this->insertData(self::KDT_ORDERS_TABLE,$data['orders']);
        $this->insertData(self::KDT_CONSIGNS_TABLE,$data['consigns']);

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return false;
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    public function pushUpdate($trade,$orders,$consign,$mod=0)
    {
        $this->db->reconnect();
        $this->db->trans_begin();

        $tradeid = $this->db->select('id,version')->from(self::KDT_TRADES_TABLE)->where('tid=',$trade['tid'])->get()->row_array();
        //push模式下校验版本号
        if (!empty($tradeid)&&$mod===1){
            //版本号低于已有版本，跳过
            if ($tradeid['version']>$trade['version']){
                return;
            }
        }
        //更新交易
        if (!empty($tradeid)){
            $this->db->update(self::KDT_TRADES_TABLE,$trade,array('id'=>$tradeid['id']));
        }else{
            $this->db->insert(self::KDT_TRADES_TABLE,$trade);
        }
        //更新订单
        $orderids = $this->db->select('id')->from(self::KDT_ORDERS_TABLE)->where('tid=',$trade['tid'])->get()->result_array();
        if (!empty($orderids)){
            $count = 0;
            foreach ($orderids as $oid){
                $this->db->update(self::KDT_ORDERS_TABLE,$orders[$count],array('id'=>$oid['id']));
                $count++;
            }
        }else{
            $this->db->insert_batch(self::KDT_ORDERS_TABLE,$orders);
        }
        //更新物流
        $consignid = $this->db->select('id')->from(self::KDT_CONSIGNS_TABLE)->where('tid=',$trade['tid'])->get()->row_array();
        if (!empty($consignid)){
            $this->db->update(self::KDT_CONSIGNS_TABLE,$consign,array('id'=>$consignid['id']));
        }else{
            $this->db->insert(self::KDT_CONSIGNS_TABLE,$consign);
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            echo 'trans fail'.PHP_EOL;
            exit();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    public function procPushData()
    {
        $this->load->model('redis_model');
        $redis = $this->redis_model->getRedisInstance();
        while (true){
            $res = $redis->lPop('kdtpush');
            if ($res===false) break;

            $data = igbinary_unserialize($res);
            if ($data['type']!=="TRADE") continue;

            $formatdata=$this->formatPushData($data['msg']['trade']);
            $redis->sAdd('kdt:salesman:trades:forupdate',$formatdata['trade']['tid']);
            $formatdata['trade']['version']=(int)$data['version'];
            $this->pushUpdate($formatdata['trade'],$formatdata['orders'],$formatdata['consign'],1);
        }
    }

    public function formatPushData($data)
    {
        $trade = array();
        $orders = array();
        $consign = array();

        $trade['tid']         = $data['tid'];//订单号
        $trade['type']        = $this->getTradeType($data['type']);//交易类型
        $trade['buyerFansType']     = isset($data['fans_info']['fans_type'])?(int)$data['fans_info']['fans_type']:0;//买家粉丝类型
        $trade['buyerFansId']     = isset($data['fans_info']['fans_id'])?(int)$data['fans_info']['fans_id']:0;//买家粉丝类型
        $trade['goodsNum']    = (int)$data['num'];//商品数量
        $trade['goodskind']   = (int)$data['goods_kind'];//商品种类
        $trade['totalFee']    = ((float)$data['total_fee'])*100;//商品总价（商品价格乘以数量的总金额）
        $trade['discountFee'] = ((float)$data['discount_fee'])*100;//交易优惠金额（不包含order中的优惠金额）
        $trade['postFee']     = ((float)$data['post_fee'])*100;//邮费
        $trade['refundFee']   = ((float)$data['refunded_fee'])*100;//交易完成后退款的金额
        $trade['payment']     = ((float)$data['payment'])*100;//实付金额
        $trade['status']      = $this->getStatus($data['status']);//交易状态
        $trade['buyerMsg']    = $data['buyer_message'];//卖家留言
        $trade['tradeMemo']   = $data['trade_memo'];//卖家对该交易的备注
        //0 无维权，1 顾客发起维权，2 顾客拒绝商家的处理结果，3 顾客接受商家的处理结果，9 商家正在处理,101 维权处理中,110 维权结束。
        //备注：1到10的状态码是微信维权状态码，100以上的状态码是有赞维权状态码
        $trade['feedback']    = (int)$data['feedback'];
        $trade['created']     = strtotime($data['created']);//交易创建时间
        $trade['changed']     = strtotime($data['update_time']);//交易更新时间。当交易的：状态改变、备注更改、星标更改 等情况下都会刷新更新时间
        $trade['payTime']     = strtotime($data['pay_time']);//买家付款时间
        $trade['consignTime'] = strtotime($data['consign_time']);//卖家发货时间
        $trade['signTime']    = empty($data['sign_time'])?0:strtotime($data['sign_time']);//买家签收时间

        foreach ($data['orders'] as $order){
            $oitem['tid']           = $trade['tid'];
            $oitem['title']         = $order['title'];//商品标题
            $oitem['num']           = (int)$order['num'];//商品购买数量
            $oitem['price']         = ((float)$order['price'])*100;//商品价格
            $oitem['totalFee']      = ((float)$order['total_fee'])*100;//应付金额（商品价格乘以数量的总金额）
            $oitem['discountFee']   = ((float)$order['discount_fee'])*100;//order的优惠金额
            $oitem['payment']       = ((float)$order['payment'])*100;//实付金额
            $oitem['fenxiaoPrice']  = ((float)$order['fenxiao_price'])*100;//商品在分销商那边的出售价格。如果是采购单才有值，否则值为 0
            $oitem['fenxiaoPayment']= ((float)$order['fenxiao_payment'])*100;//商品在分销商那边的实付金额。如果是采购单才有值，否则值为 0
            $oitem['num_iid']       = isset($order['num_iid'])?$order['num_iid']:$order['item_id'];//商品数字编号
            $oitem['item_type']     = $order['item_type'];//商品类型。0：普通商品;10：分销商品;
            $oitem['status']        = $trade['status'];
            $oitem['created']       = $trade['created'];
            $oitem['changed']       = $trade['changed'];
            $orders[] = $oitem;
        }

        $consign['tid']     = $trade['tid'];
        $consign['zip'] = $data['receiver_zip'];//邮编
        $consign['province']= $data['receiver_state'];
        $consign['city']    = $data['receiver_city'];
        $consign['district']= $data['receiver_district'];
        $consign['address'] = $data['receiver_address'];
        $consign['receiver']= $data['receiver_name'];
        $consign['mobile']  = $data['receiver_mobile'];
        $consign['shipType']= $this->getShipType($data['shipping_type']);//express（快递），fetch（到店自提），local（同城配送
        $consign['created'] = $trade['created'];
        return array('trade'=>$trade,'orders'=>$orders,'consign'=>$consign);
    }

    public function updateTradesOrdersConsigns($apidata,$echoindex)
    {
        foreach ( $apidata as $trade )
        {
            $res = $this->formatPushData($trade);
            $this->pushUpdate($res['trade'],$res['orders'],$res['consign']);
            echo $echoindex." ".$res['trade']['tid'].' complete'.PHP_EOL;
            $echoindex++;
        }
    }
    
    public function getTradeType($type)
    {
        //交易类型
        switch ($type){
            //一口价
            case 'FIXED':
                $res = 1;
                break;
            //送礼
            case 'GIFT':
                $res = 2;
                break;
            //来自分销商的采购
            case 'BULK_PURCHASE':
                $res = 3;
                break;
            //赠品领取
            case 'PRESENT':
                $res = 4;
                break;
            //拼团订单
            case 'GROUP':
                $res = 5;
                break;
            //批发订单
            case 'PIFA':
                $res = 6;
                break;
            //货到付款
            case 'COD':
                $res = 7;
                break;
            //代付
            case 'PEER':
                $res = 8;
                break;
            //扫面商家二维码直接支付的交易
            case 'QRCODE':
                $res = 9;
                break;
            //线下收银台二维码交易
            case 'QRCODE_3RD':
                $res = 10;
                break;
            default:
                $res = 0;
        }
        return $res;
    }

    public function getStatus($status)
    {
        //交易状态
        switch ($status){
            case 'TRADE_NO_CREATE_PAY':
                $res = 1;
                break;
            //等待买家付款
            case 'WAIT_BUYER_PAY':
                $res = 2;
                break;
            //等待成团，即：买家已付款，等待成团
            case 'WAIT_GROUP':
                $res = 4;
                break;
            //等待卖家发货，即：买家已付款
            case 'WAIT_SELLER_SEND_GOODS':
                $res = 5;
                break;
            //等待买家确认收货，即：卖家已发货
            case 'WAIT_BUYER_CONFIRM_GOODS':
                $res = 6;
                break;
            //买家已签收
            case 'TRADE_BUYER_SIGNED':
                $res = 7;
            break;
            //付款以后用户退款成功，交易自动关闭
            case 'TRADE_CLOSED':
                $res = 8;
                break;
            //付款以前，卖家或买家主动关闭交易
            case 'TRADE_CLOSED_BY_USER':
                $res = 9;
                break;
            default:
                $res = 0;
        }
        return $res;
    }

    public function getShipType($ship)
    {
        switch ($ship){
            case 'express':
                $res = 1;
                break;
            case 'fetch':
                $res = 2;
                break;
            case 'local':
                $res = 3;
                break;
            default:
                $res = 0;
        }
        return $res;
    }

    public function systrades()
    {
        try {
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            while (true) {
                $msg = $redis->blPop('kdtpush', 0);
                $msg = igbinary_unserialize($msg[1]);
                $res=$this->formatPushData($msg['trade']);
                $this->pushUpdate($res['trade'],$res['orders'],$res['consign']);
            }
        }catch (Exception $e){
            $err['type'] = 'kdtpush';
            $err['time'] = date('Y-m-d H:i:s',time());
            $err['data'] = 'kdtpush error : '.$e->getMessage();
            $err = igbinary_serialize($err);
            $this->redis_model->rpush('errlist',$err);
            $this->db->close();
            exit();
        }
    }

    /*
     * 销售员信息
     * */
    public function updateSalesmanList($apidata)
    {
        $itemno = 1;
        foreach ( $apidata as $sm )
        {
            $res = $this->formatSMData($sm);
            $this->smUpdate($res);
            echo $itemno.' '.$res['name'].' complete'.PHP_EOL;
            $itemno++;
        }
    }

    public function formatSMData($data)
    {
        $res = array();

        $res['phone']  = trim($data['mobile']);
        $res['name']   = trim($data['nickname']);
        $res['idcode'] = trim($data['seller']);
        $res['created'] = strtotime(trim($data['created_at']));
        $res['fans_id']= (int)$data['fans_id'];
        $res['invifrom']=trim($data['from_buyer_mobile']);
        $res['type']=preg_match('/PCFI/i',$res['name'])>0?'PCFI':'NLDOU';

        return $res;
    }

    public function smUpdate($data)
    {
        $this->db->reconnect();
        $this->db->trans_begin();

        $smid = $this->db->select('id')->from(self::KDT_SALESMAN)->where('idcode',$data['idcode'])->get()->row_array();
        if (!empty($smid)){
            $this->db->update(self::KDT_SALESMAN,$data,array('id'=>$smid['id']));
        }else{
            $this->db->insert(self::KDT_SALESMAN,$data);
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            echo 'trans fail'.PHP_EOL;
            exit();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }

    public function updateTrades($start,$end)
    {
        $this->load->model('kdt_api_model');
        $pageno = 1;
        $pagesize = 50;
        $start = date('Y-m-d H:i:s', $start);
        $end = date('Y-m-d H:i:s', $end);
        echo $start.'~'.$end.PHP_EOL;
        while (true) {
            $stepdata = $this->kdt_api_model->getTradesSold($start,$end,$pageno,$pagesize);
            $index = $pagesize * $pageno + 1;
            $this->updateTradesOrdersConsigns($stepdata['trades'], $index);
            if (!$stepdata['has_next']) break;
            $pageno++;
        }

    }

    /*
     * 销售员订单信息
     * */
    public function updateSalesmanTrades($mobile,$start,$end)
    {
        $this->load->model('kdt_api_model');
        $start = strtotime($start);
        $end   = strtotime($end);
        $step=24*30*3600;
        $dur=$end-$start;
        $loop=$dur<$step?1:ceil($dur/$step);
        $stop=$start+$step;

        while (true){
            if ($loop == 0||$loop < 0) break;
            //获取一段时间该代言人的订单
            $stepdata = $this->kdt_api_model->getSalesmanTrades($mobile,$start,$stop);
            $this->updateSalesmanTradesOrders($stepdata);

            $loop--;
            $start+=$step;
            $stop +=$step;
        }

    }

    public function updateSalesmanTradesOrders($apidata)
    {
        foreach ( $apidata as $trade )
        {
            $res = $this->formatSMTradesData($trade);
            $this->smTradesUpdate($res['trade'],$res['orders']);
            echo $res['trade']['tid'].' complete'.PHP_EOL;
        }
    }

    public function formatSMTradesData($data)
    {
        $trade = array();
        $orders = array();

        $trade['tid']         = trim($data['order_no']);//订单号
        $trade['idcode']      = trim($data['seller']);//销售员ID
        $trade['cps_money']   = (float)$data['cps_money']*100;//提成金额，单位：元->分
        $trade['created']     = strtotime($data['created_at']);//下单时间
        $trade['state']       = (int)$data['state'];//订单状态:3:待付款，5:已付款，6:已发货，100:交易完成
        $trade['settle_state']= (int)$data['settle_state'];//结算状态:1:待结算 2:已结算 3:余额不足 4:结算异常，等待重试 5:货到付款
        $trade['auto_settle'] = (int)$data['auto_settle'];//是否自动结算0:人工结算1:自动结算

        foreach ($data['items'] as $order){
            $oitem['tid']           = $trade['tid'];//订单号
            $oitem['title']         = $order['title'];//商品标题
            $oitem['num']           = (int)$order['num'];//商品购买数量
            $oitem['price']         = (float)$order['price']*100;//商品价格，单位：元->分
            $oitem['is_join']       = (int)$order['is_join'];//商品是否参与推广:0:不参与1参与
            $oitem['num_iid']       = $order['num_iid'];//商品ID
            $oitem['i_rate']        = (float)$order['i_rate']*100;//商品提成比例(单位：%->%%)
            $oitem['ii_rate']       = (float)$order['ii_rate']*100;//商品邀请奖励提成比例(单位：%->%%)
            $oitem['i_cps_money']   = (float)$order['i_cps_money']*100;//商品提成奖励(单位：元->分)
            $oitem['ii_cps_money']  = (float)$order['ii_cps_money']*100;//商品邀请奖励提成奖励(单位：元->分)
            $oitem['created']       = $trade['created'];

            $orders[] = $oitem;
        }

        return array('trade'=>$trade,'orders'=>$orders);
    }

    public function smTradesUpdate($trade,$orders)
    {
        $this->db->reconnect();
        $this->db->trans_begin();
        //更新交易
        $tradeid = $this->db->select('id')->from(self::KDT_SM_TRADE)->where('tid=',$trade['tid'])->get()->row_array();
        if (!empty($tradeid)){
            $this->db->update(self::KDT_SM_TRADE,$trade,array('id'=>$tradeid['id']));
        }else{
            $this->db->insert(self::KDT_SM_TRADE,$trade);
        }
        //更新订单
        $orderids = $this->db->select('id')->from(self::KDT_SM_ORDER)->where('tid=',$trade['tid'])->get()->result_array();
        if (!empty($orderids)){
            $count = 0;
            foreach ($orderids as $oid){
                $this->db->update(self::KDT_SM_ORDER,$orders[$count],array('id'=>$oid['id']));
                $count++;
            }
        }else{
            $this->db->insert_batch(self::KDT_SM_ORDER,$orders);
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            echo 'trans fail'.PHP_EOL;
            exit();
        }
        else
        {
            $this->db->trans_commit();
            return true;
        }
    }


}